<?php

namespace Kateba\AdminBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Kateba\SiteBundle\Entity\Message;
use Kateba\SiteBundle\Form\MessageType;

/**
 * Message controller.
 * @author Mahmoud
 */
class MessageController extends Controller {

    private function markMessagesAsRead($messages) {
        foreach ($messages as $message) {
            if (!$message->getIsAdmin() && $message->getIsNew()) {
                $message->setIsNew(false);
                $message->getUser()->setNewMessagesCount($message->getUser()->getNewMessagesCount() - 1);
            }
        }
        $this->getDoctrine()->getEntityManager()->flush();
    }

    public function userMessagesAction($loginName) {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $em->getRepository('KatebaUserBundle:User')->findOneByLoginName($loginName);
        if (!$user) {
            throw $this->createNotFoundException();
        }
        $maxResults = 10;
        $messages = $em->getRepository('KatebaSiteBundle:Message')->getLatestMessages($user->getId(), $maxResults + 1);
        $lastMessageId = 0;
        $firstMessageId = 0;
        $messagesCount = count($messages);
        if ($messagesCount > 0) {
            $lastMessageId = $messages[0]->getId();
            if ($messagesCount > $maxResults) {
                $firstMessageId = $messages[$maxResults - 1]->getId();
                array_pop($messages);
            }
        }
        $message = new Message();
        $message->setUser($user);
        $message->setIsAdmin(true);
        $form = $this->createForm(new MessageType(), $message);
        $this->markMessagesAsRead($messages);
        return $this->render('KatebaAdminBundle:Message:userMessages.html.twig', array(
                    'messages' => array_reverse($messages),
                    'lastMessageId' => $lastMessageId,
                    'firstMessageId' => $firstMessageId,
                    'form' => $form->createView(),
                    'user' => $user
        ));
    }

    public function createAction($loginName, Request $request) {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $em->getRepository('KatebaUserBundle:User')->findOneByLoginName($loginName);
        if (!$user) {
            throw $this->createNotFoundException();
        }
        $message = new Message();
        $message->setUser($user);
        $message->setIsAdmin(true);
        $form = $this->createForm(new MessageType(), $message);
        $form->bind($request);

        if ($form->isValid()) {
            $userNotify = $user->getMessageNotify();
            $em->persist($message);
            $em->flush();
            if ($userNotify) {
                $subject = 'Educino - New Admin Message';
                $message = $this->renderView('KatebaAdminBundle:Message:newMessageEmail.html.twig', array('user' => $user));
                $headers = 'From: Educino <' . $this->container->getParameter('admin_notifications_email') . '>' . "\r\n";
                $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
                mail($user->getEmail(), $subject, $message, $headers);
                
//                $message = \Swift_Message::newInstance()
//                        ->setSubject('Educino - New Admin Message')
//                        ->setFrom($this->container->getParameter('admin_notifications_email'))
//                        ->setTo($user->getEmail())
//                        ->setBody($this->renderView('KatebaAdminBundle:Message:newMessageEmail.html.twig', array(
//                            'user' => $user
//                        )), 'text/html')
//
//                ;
//                $this->get('mailer')->send($message);
            }
            // clear the form
            $message = new Message();
            $form = $this->createForm(new MessageType(), $message);
        }
        return $this->render('KatebaAdminBundle:Message:newUserMessageForm.html.twig', array(
                    'form' => $form->createView(),
                    'user' => $user
        ));
    }

    public function newUserMessagesAction($loginName, $id) {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $em->getRepository('KatebaUserBundle:User')->findOneByLoginName($loginName);
        if (!$user) {
            throw $this->createNotFoundException();
        }
        $messages = $em->getRepository('KatebaSiteBundle:Message')->getNewerMessages($user->getId(), $id);
        $lastMessageId = $id;
        if (count($messages) > 0) {
            $lastMessageId = $messages[0]->getId();
            $messages = array_reverse($messages);
        }
        $this->markMessagesAsRead($messages);
        $data = array();
        $data['lastMessageId'] = $lastMessageId;
        $data['messages'] = $this->renderView('KatebaAdminBundle:Message:messages.html.twig', array('messages' => $messages));
        return new Response(json_encode($data), 200, array('Content-Type' => 'application/json'));
    }

    public function oldUserMessagesAction($loginName, $id) {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $em->getRepository('KatebaUserBundle:User')->findOneByLoginName($loginName);
        if (!$user) {
            throw $this->createNotFoundException();
        }
        $maxResults = 10;
        $messages = $em->getRepository('KatebaSiteBundle:Message')->getOlderMessages($user->getId(), $id, $maxResults + 1);
        $firstMessageId = 0;
        $messagesCount = count($messages);
        if ($messagesCount > 0) {
            $messages = array_reverse($messages);
            if ($messagesCount > $maxResults) {
                array_shift($messages);
                $firstMessageId = $messages[0]->getId();
            }
        }
        $this->markMessagesAsRead($messages);
        $data = array();
        $data['firstMessageId'] = $firstMessageId;
        $data['messages'] = $this->renderView('KatebaAdminBundle:Message:messages.html.twig', array('messages' => $messages));
        return new Response(json_encode($data), 200, array('Content-Type' => 'application/json'));
    }

    public function getUnreadMessagesCountAction() {
        return new Response($this->getDoctrine()->getRepository('KatebaSiteBundle:Message')->getAdminUserUnreadMessagesCount());
    }

    public function getNewMessagesCountAction($loginName, $id) {
        $em = $this->getDoctrine()->getEntityManager();
        $user = $em->getRepository('KatebaUserBundle:User')->findOneByLoginName($loginName);
        if (!$user) {
            throw $this->createNotFoundException();
        }
        return new Response($em->getRepository('KatebaSiteBundle:Message')->getNewerMessagesCount($user->getId(), $id));
    }

}
